﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AvalSqlIndexManager.Models
{
    public class TableIndex
    {
        public string? Name { get; set; }
        public string TableName { get; set; }

        public string FieldsName { get; set; }
        public string? FieldsInclude { get; set; }

        public string? CorpName { get; set; }

        public DateTime CreateTime { get; set; }

        public TableIndex()
        {
            TableName = string.Empty;
            FieldsName = string.Empty;
            CreateTime = DateTime.Now;
        }

        public string GetIndexName()
        {
            string indexName = $"IX_{TableName}";            
            string[] arr = this.FieldsName.Split(',');
            for (int i = 0; i < 2; i++)
            {
                if (arr.Length > i)
                    indexName += $"_{arr[i]}";
            }
            return indexName ;
        }
        public string BuildCreateSql()
        {
            string indexName = $"IX_{TableName}";            
            StringBuilder sb = new StringBuilder();
            string[] arr = this.FieldsName.Split(',');
            for(int i = 0; i < 2; i++)
            {
                if (arr.Length > i)
                    indexName += $"_{arr[i]}";
            }
            sb.AppendFormat(@"--创建索引
if not exists (select 1 from sys.indexes
               where object_id=OBJECT_ID('{0}',N'U') 
               and name='{1}')
begin
create nonclustered index [{1}] 
on [{0}] (
    ", TableName,indexName);
            sb.Append(string.Join(",",arr));
            if(!string.IsNullOrEmpty(FieldsInclude))
            {
                sb.Append("\r\n) include (\r\n    ");
                string[] arrClude = FieldsInclude.Split(",");
                sb.Append(string.Join(",",arrClude));                
            }
            sb.Append(@"
)
end");
            return sb.ToString();
        }
    }
}
